package com.common;

import lombok.Getter;

@Getter
public enum EquityStatus {
    DRAFT(0, 0b001,"草稿状态"),
    UNDER_REVIEW(1, 0b010,"审核中状态"),
    APPROVED(2, 0b100,"审核通过"),
    REJECTED(3, 0b1000,"审核驳回"),
    ONLINE(4, 0b10000,"上线状态"),
    OFFLINE(5, 0b100000,"下线状态");

    private final int code;
    private final int mask;
    private final String description;
    EquityStatus(int code, int mask, String description) {
        this.code = code;
        this.mask = mask;
        this.description = description;
    }

    public int getCode() {
        return code;
    }

    public int getMask() {
        return mask;
    }

    public String getDescription() {
        return description;
    }

    @Override
    public String toString() {
        return this.name() + "(" + this.code + " - " + this.description + ")";
    }
    // 定义状态转换规则
    private static final int[] TRANSITIONS = {
            DRAFT.mask | UNDER_REVIEW.mask | OFFLINE.mask,           // 草稿状态可以转换为下线、审核中
            UNDER_REVIEW.mask | REJECTED.mask | APPROVED.mask,        // 审核中状态可以转换为审核驳回、审核通过
            APPROVED.mask | ONLINE.mask | OFFLINE.mask,               // 审核通过状态可以转换为上线、下线
            REJECTED.mask | UNDER_REVIEW.mask | OFFLINE.mask,         // 审核驳回状态可以转换为下线、审核中
            ONLINE.mask | OFFLINE.mask,                               // 上线状态可以转换为下线
            DRAFT.mask | UNDER_REVIEW.mask                            // 下线状态可以转换为草稿、审核中
    };
    // 检查是否可以执行状态转换
    public static boolean canTransition(EquityStatus currentState, EquityStatus nextState) {
        return (TRANSITIONS[currentState.ordinal()] & nextState.mask) == nextState.mask;
    }

    public static EquityStatus fromCode(int code) {
        for (EquityStatus status : EquityStatus.values()) {
            if (status.code == code) {
                return status;
            }
        }
        throw new IllegalArgumentException("Unknown code: " + code);
    }

    public static EquityStatus fromString(String text) {
        for (EquityStatus status : EquityStatus.values()) {
            if (status.name().equalsIgnoreCase(text) || status.description.equals(text)) {
                return status;
            }
        }
        throw new IllegalArgumentException("Unknown status: " + text);
    }

}
